#include <webx/route.h>
#include <http/HttpHelper.h>

class GetWords : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(GetWords)

int GetWords::process()
{
	param_string(key);
	
	if (key.empty()) return simpleResponse(XG_PARAMERR);

	const char* url = "http://suggestion.baidu.com/su?wd=";
	SmartBuffer data = HttpHelper::GetResult(url + stdx::EncodeURL(key) + "&cb=updatewords");

	if (data.size() < 16) return simpleResponse(XG_SYSERR);

	int res = 0;
	string tmp = stdx::utfcode(data.str());

	if (tmp.length() > 0)
	{
		char* msg = (char*)tmp.c_str();
		char* str = (char*)strchr(msg, '[');
		char* end = (char*)strrchr(msg, ']');

		if (str && end && end > str)
		{
			end[1] = 0;

			JsonElement vec(str);
			JsonElement arr = json["list"];

			for (JsonElement item : vec)
			{
				arr[res++] = item.asString();
			}
		}
	}

	json["code"] = res;
	out << json;

	return XG_OK;
}